<template>
    <div id="left-menu">
      <el-row class="tac">
        <el-col :span="24">
          <h5><i class="el-icon-shopping-cart-2" style="font-size: 16px"></i>购物车</h5>
          <el-menu
            v-for="item in category"
            default-active="2"
            class="el-menu-vertical-demo"
            @open="handleOpen"
            @close="handleClose"
            background-color="#545c64"
            text-color="#fff"
            active-text-color="#ffd04b">
            <el-submenu index="1">
              <template slot="title">
                <i class="el-icon-menu"></i>
                <span>{{item}}</span>
              </template>
              <el-menu-item-group v-for="book in getBooks(item)">
                <template slot="title">{{book.bookName+'（' + book.author +'）：' + book.num}}</template>
                <el-menu-item index="1-1" @click="bookAdd(book)" style="user-select: none">添加</el-menu-item>
                <el-menu-item index="1-2" @click="bookRemove(book)" style="user-select: none">移除</el-menu-item>
              </el-menu-item-group>
            </el-submenu>
          </el-menu>
          <el-menu
            default-active="2"
            class="el-menu-vertical-demo"
            @open="handleOpen"
            @close="handleClose"
            background-color="#545c64"
            text-color="#fff"
            active-text-color="#ffd04b">
            <el-menu-item index="2">
              <i class="el-icon-shopping-cart-full"></i>
              <span slot="title">总计{{total}}</span>
            </el-menu-item>
            <el-menu-item index="3" @click="clear">
              <i class="el-icon-remove-outline"></i>
              <span slot="title">清空购物车</span>
            </el-menu-item>
          </el-menu>
        </el-col>
      </el-row>

    </div>
</template>

<script>
  export default {
    name: "LeftMenu",
    computed: {
      total() {
        let sum = 0
        this.category.forEach((item, index)=>{
          this.getBooks(item).forEach((it, ind)=>{
            sum += it.num * it.price
          })
        })
        return sum.toFixed(2)
      }
    },
    methods: {
      handleOpen(key, keyPath) {
        console.log(key, keyPath);
      },
      handleClose(key, keyPath) {
        console.log(key, keyPath);
      },
      getBooks(type) {
        let list = []
        this.books.forEach((item, index)=>{
          if (item.category === type && item.num !== 0) {
            list.push(item)
          }
        })
        return list
      },
      bookAdd(book) {
        book.num ++
      },
      bookRemove(book) {
        book.num --
      },
      clear() {
        this.books.forEach((item, index)=>{
          item.num = 0
        })
      }
    },
    props: {
      category: {
        default() {
          return []
        }
      },
      books: {
        default() {
          return []
        }
      }
    }
  }
</script>

<style scoped>

</style>
